//
//  WBQAuthcONTROLLERViewController.swift
//  swiftweibo
//
//  Created by ffxk007 on 2017/6/20.
//  Copyright © 2017年 ffxk007. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBQAuthcONTROLLERViewController: UIViewController {

    fileprivate lazy var webview = UIWebView()
    
    override func loadView() {
        view = webview
        view.backgroundColor = UIColor.white
        //取消滚动视图 新浪微博的服务器，返回的授权页面默认就是手机全屏
        webview.scrollView.isScrollEnabled = false
        //设置代理
        webview.delegate = self
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fonSize: 16.0, target: self, action: #selector(close), isBackButton: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autofull))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppkey)&redirect_uri=\(WBRedirectURL)"
        
        guard let url = URL(string: urlString) else {
            return
        }
        
        let request = URLRequest(url: url)
        
        webview.loadRequest(request)
        
        
    }

   
    //MARK:-监听方法
    @objc fileprivate func close() {
        dismiss(animated: true, completion: nil)
        SVProgressHUD.dismiss()
    }
    //自动填充 webview的注入 直接通过js修改‘本地浏览器中’缓存的页面的内容
    //点击登录按钮 执行sumbit() 将本地数据提交给服务器
    @objc fileprivate func autofull() {
        let js = "document.getElementById('userId').value = '18710479563';" + "document.getElementById('passwd').value = 'fxk192837';"
        webview.stringByEvaluatingJavaScript(from: js)
    }
}

extension WBQAuthcONTROLLERViewController:UIWebViewDelegate {
   
    /// webview将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webview
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       
        //如果请求地址包含http://baidu.com不加载页面 否则加载页面
        if (request.url?.absoluteString.hasPrefix(WBRedirectURL)) == false {
            return true
        }
        
//        print("加载请求----\(String(describing: request.url?.absoluteString))")
//        print("加载请求----\(String(describing: request.url?.query))")
        //从http://baidu.com回调地址查找字符串中查找code  如果有授权成功 否则授权失败
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            
            close()
            return false
        }
        
        //代码走到此处，url中一定有查询字符串并且包含code
       let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码 \(code)")
        //获取授权码
        WBNetworkManger.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
//                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                //跳转界面 通过通知发送登录成功的消息
                //发送通知 b不关心有没有监听者
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),
                    object: nil)
                
                //关闭窗口
                self.close()
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
